var express = require('express');
var router = express.Router();
var accountList = require('../../../data/account-data');
var roleList = require('../../../data/role-data');
var bridges = require('../../../data/account-role-bridge-data');
var _ = require('underscore');
var pagination = require('../../../utils/pagination')();
var MessageModel = require("../../../model/iotek-message")();

router.get('/', function (request, response, next) {
    var pn, ps, keyword, sortBy, asc;
    pn = +request.query['pn'] || 1;
    ps = +request.query['ps'] || 10;
    keyword = request.query['keyword'];
    sortBy = request.query['sortBy'];
    asc = request.query['asc'];
    asc = asc === 'true';
    var limitedAccounts = getLimitedAccount(pn, ps, keyword, sortBy, asc);
    response.json(limitedAccounts);
});

router.delete('/:id', function (request, response, next) {
    try {
        var id = +request.params['id'];
        var deletedList = _.reject(accountList, function (role) {
            return role.id == id;
        });
        accountList = deletedList;
        deleteBridgeByAccountId(id);
    } catch (e) {
        response.json(new MessageModel('FAILED', "删除失败了", "不知咋滴，用户并被没有删除！"));
        return;
    }
    response.json(new MessageModel('SUCCESS', "删除成功", "用户已经删除成功了！"));
});

router.put('/', function (request, response) {
    var roleId, name, phone, remark;
    roleId = request.body['roleId'];
    name = request.body['name'];
    phone = request.body['phone'];
    remark = request.body['remark'];
    var errorMessages = [];
    try {
        if (!!!roleId) {
            errorMessages.push("选择的角色不存在");
        }
        if (!!!name) {
            errorMessages.push("用户名字必须填写");
        }
        if (!!!phone) {
            errorMessages.push("电话号码不能为空");
        }
        if (!!errorMessages.length) {
            throw errorMessages.join(",");
        } else {
            var newAccount = executeAddAccount(roleId, name, phone, remark);
        }
    } catch (e) {
        response.json(new MessageModel("FAILED", "添加失败", e));
        return;
    }
    response.json(new MessageModel("SUCCESS", "添加成功", newAccount));
});

router.post('/', function (request, response) {
    var id, roleId, name, phone, remark;
    id = request.body['id'];
    roleId = request.body['roleId'];
    name = request.body['name'];
    phone = request.body['phone'];
    remark = request.body['remark'];
    var errorMessages = [];
    try {
        if (!!!id) {
            errorMessages.push("不知道侬选了谁");
        }
        if (!!!roleId) {
            errorMessages.push("选择的角色不存在");
        }
        if (!!!name) {
            errorMessages.push("用户名字必须填写");
        }
        if (!!!phone) {
            errorMessages.push("电话号码不能为空");
        }
        if (!!errorMessages.length) {
            throw errorMessages.join(",");
        } else {
            var newAccount = executeUpdateAccount(id, roleId, name, phone, remark);
        }
    } catch (e) {
        response.json(new MessageModel("FAILED", "更新失败", e));
        return;
    }
    response.json(new MessageModel("SUCCESS", "更新成功", newAccount));
});


Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

function getLimitedAccount(pn, ps, keyword, sortBy, asc) {
    var newList = accountList;
    var allList = accountList;
    if (keyword) {
        allList = _.filter(accountList, function (account) {
            return account.username.lastIndexOf(keyword) != -1;
        })
    }
    newList = pagination(pn, ps, allList);
    if (sortBy) {
        newList = _.sortBy(newList, sortBy);
        if (!asc) {
            newList = newList.reverse();
        }
    }

    for (var i in newList) {
        var accountId = newList[i].id;
        var tempRole = getRoleByAccountId(accountId);
        newList[i].roleName = tempRole.name;
        newList[i].roleId = tempRole.id;

    }
    var result = {
        "totalPage": Math.ceil(allList.length / ps),
        "totalItems": allList.length,
        "pn": pn,
        "ps": ps,
        resultList: newList
    };
    console.log(newList);

    return result;
}

function executeAddAccount(roleId, name, phone, remark) {
    var maxAccount = _.max(accountList, function (account) {
        return account.id;
    });
    var maxId = maxAccount.id + 1;
    var newAccount = {
        "id": maxId,
        "unitId": null,
        "username": name,
        "realName": "",
        "password": "E10ADC3949BA59ABBE56E057F20F883E",
        "type": 1,
        "comment": remark,
        "enabled": 1,
        "createTime": new Date().Format("yyyy-MM-dd hh:mm:ss"),
        "lastLoginTime": new Date().Format("yyyy-MM-dd hh:mm:ss"),
        "createUser": null,
        "phoneNumber": phone
    };
    accountList.push(newAccount);
    // 更新关联表
    var maxRA = _.max(bridges, function (b) {
        return b.id;
    });
    var maxRAId = maxRA.id;
    bridges.push({
        "id": ++maxRAId,
        "accountId": maxId,
        "roleId": roleId,
        "createUser": 1,
        "updateUser": 1179,
        "createTime": new Date().Format("yyyy-MM-dd hh:mm:ss"),
        "updateTime": new Date().Format("yyyy-MM-dd hh:mm:ss")
    });
    return newAccount;
}

function executeUpdateAccount(id, roleId, name, phone, remark) {
    var findFlag = false;
    var account;
    for (var i in accountList) {
        account = accountList[i];
        if (account.id == id) {
            account.username = name;
            account.phoneNumber = phone;
            account.comment = remark;
            findFlag = true;
            break;
        }
    }
    // 更新关联表
    for (var index in bridges) {
        var b = bridges[index];
        if (b.id == id) {
            b.roleId = roleId;
            break;
        }
    }
    if (!findFlag) throw "更新失败了， 原因是没找到你传的那个账户!";
    return account;
}

function getRoleByAccountId(accountId) {
    var targetRole = _.find(bridges, function (b) {
        return b.accountId == accountId;
    });
    if(!targetRole) {return "未知角色"}
    var role = _.find(roleList, function (role) {
        return role.id == targetRole.roleId;
    });
    return role
}

function deleteBridgeByAccountId(accountId) {
    bridges = _.reject(bridges, function (b) {
        return b.accountId == accountId;
    })
}

module.exports = router;
